<?php

namespace App\Http\Controllers\Api;

use App\Model\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AddressController extends BaseController {
    //收货地址


    private $user;
    public function __construct(){
        $this->user=$this->GetUser();
    }


    //收货地址列表
    public function lists(){
        $data['user_id']=$this->user['user_id'];

        $list=DB::table('user_address')->where($data)->get()->each(function ($item,$key){
            $user=DB::table('user')->where('user_id',$item->user_id)->first();
            if ($user->address_id==$item->address_id){
                $item->defind=1;
            }else{
                $item->defind=0;
            }
            return $item;
        });
        return json_encode($list);
    }

    //添加收货地址
    public function add(Request $request){
    $data=$request->all();
    $data['create_time']=time();
    $data['update_time']=time();
    $data['user_id']=$this->user['user_id'];
    unset($data['token']);
    $res=DB::table('user_address')->insertGetId($data);
    if ($res>0){
        return ['code'=>1,'msg'=>'添加成功','address_id'=>$res];
    }else{
        return ['code'=>0,'msg'=>'添加失败'];
       }
    }

   //地址详情
   public function detail(Request $request){
       $address_id=$request->route('address_id');
       $data=Address::find($address_id);
       return ['data'=>$data];

   }

     //编辑收货地址
    public function edit(Request $request){
        $data=$request->all();
        $data['update_time']=time();
        $data['user_id']=$this->user['user_id'];
        unset($data['token']);
        $res=Address::where('address_id',$data['address_id'])->update($data);
        if ($res){
            return ['code'=>1,'msg'=>'更新成功'];
        }else{
            return ['code'=>0,'msg'=>'更新失败'];
        }
    }

     //设为默认地址
     public function setDefault(Request $request){
        $data['address_id']=$request->input('address_id');
         $res=DB::table('user')->where('user_id',$this->user['user_id'])->update($data);
         if ($res){
             return ['code'=>1,'msg'=>'设置成功'];
         }else{
             return ['code'=>0,'msg'=>'设置失败'];
         }

     }

      //删除收货地址
     public function del(Request $request){
        $address_id=$request->input('address_id');
        $res=Address::destroy($address_id);
        if ($res){
         return ['code'=>1,'msg'=>'删除成功'];
        }else{
         return ['code'=>0,'msg'=>'删除失败'];
         }
     }

}
